package com.zhuhjay.common.security.config;

import com.zhuhjay.common.base.constant.ApplicationConstant;
import com.zhuhjay.common.security.custom.SecurityFilterHolder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @author ZhuHJay
 * @date 2023/2/24 23:34
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Bean
    @ConfigurationProperties(prefix = "security")
    public SecurityProperty securityProperty() {
        return new SecurityProperty();
    }

    /** 密码明文加密方式配置 **/
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /** 获取AuthenticationManager（认证管理器），登录时认证使用 **/
    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /** SpringSecurity5.7 推荐使用 **/
    @Bean
    public SecurityFilterChain filterChain(
            HttpSecurity http, UserDetailsService userDetailsService,
            SecurityFilterHolder securityFilterHolder) throws Exception {
        // CSRF禁用，因为不使用session
        http.csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .headers().frameOptions().disable();

        http.userDetailsService(userDetailsService)
                // 添加token校验过滤器
                .addFilter(securityFilterHolder.authenticationFilter())
                // 自定义认证失败处理器
                .exceptionHandling().authenticationEntryPoint(securityFilterHolder.authenticationEntryPoint()).and()
                // 配置请求过滤规则
                .authorizeRequests()
                // 放行静态资源
                .antMatchers(securityProperty().getAuthWhite()).permitAll()
                .anyRequest().authenticated();

        http.logout()
                // 登出请求匹配器
                .logoutRequestMatcher(new AntPathRequestMatcher(ApplicationConstant.LOGOUT_REQUEST_MATCHER, ApplicationConstant.LOGOUT_REQUEST_METHOD))
                // 登出成功后删除token
                .addLogoutHandler(securityFilterHolder.logoutHandler())
                // 登出成功处理器
                .logoutSuccessHandler(securityFilterHolder.logoutSuccessHandler());
        return http.build();
    }

}
